#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <assert.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/dir.h>
#include <sys/stat.h>

#include "bstrlib.h"
#include "server.h"
#include "fd_list.h"
#include "common.h"
#include "to_index.h"

int send_hello(fd_list list, int i, int global_port){
    int fd=0;
    char *port;

    port = calloc(7, sizeof(char*));
    fd = fd_list_get_fd(list, i);

    if(send_msg(fd, "hello ")!=0)
        return -1;

    sprintf(port, "%i",global_port);

    if(send_msg(fd, port)!=0)
        return -1;
    if(send_msg(fd, "\r\n")!=0)
        return -1;

    free(port);
    port = NULL;
    return 1;

}

int
load_get_file_listing(fd_list list, char* std_in){
    int i=0, fd_client=0;

    for (i=0; i<fd_list_size(list); i++){
        if (fd_list_is_index(list, i) && 
            fd_list_has_finished_attending(list, i)){
            fd_client = fd_list_get_fd(list, i);
            if(send_msg(fd_client, "get_file_listing ")!=0)
                return -1;
            if(send_msg(fd_client, std_in)!=0)
                return -1;
            if(send_msg(fd_client, "\r\n")!=0)
                return -1;
        }
        else if(fd_list_is_index(list, i) && 
                !fd_list_has_finished_attending(list, i)){
            printf("El tracker esta ocupado, intente nuevamente\n");
        }
    }
    return 1;
}
